<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-06 13:07:07
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Purchase;

use App\Http\Services\Service;
use App\Repositories\PurchaseComplaintRepository;
use App\Repositories\PurchaseComplaintDetailsRepository;
use Illuminate\Support\Facades\DB;

/**
 * @property PurchaseComplaintRepository $repository
 * @property PurchaseComplaintDetailsRepository $details  
 */
class ComplaintService extends Service
    {
    public $details;

    public function boot(
        PurchaseComplaintRepository $repository,
        PurchaseComplaintDetailsRepository $details,
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        }

    public function list()
        {
        $data = $this->repository->condition(request())->getGrid();
        return $data;
        }
    public function details()
        {
        // DB::enableQueryLog();
        $data = $this->details->condition(request())->getGrid();
        // dd(DB::getQueryLog());
        return $data;
        }
    protected function save()
        {
        $data = request()->toArray();

        $purchase_data['id']                 = !isEmpty($data['id'] ?? "") && $data['id'] > 0 ? $data['id'] : 0;
        $purchase_data['billdate']           = $data['billdate'];
        $purchase_data['complaint_id']       = $data['complaint_id'];
        $purchase_data['relation_code']      = $data['relation_code'];
        $purchase_data['company_id']         = $data['company_id'];
        $purchase_data['department_id']      = $data['department_id'];
        $purchase_data['remark']             = $data['remark'];
        $purchase_data['tax_id']             = $data['tax_id'];
        $purchase_data['attachments']        = $data['attachments'];
        $purchase_data['iscustomer']         = 0;
        $purchase_data['red_id']             = $data['red_id'];
        $purchase_data['material_id']        = $data['material_id'];
        $purchase_data['complaint_id']       = $data['complaint_id'];
        $purchase_data['amount']             = 0;
        $purchase_data['auxiliary_quantity'] = 0;
        $purchase_data['quantity']           = 0;
        $purchase_data['details']            = $data['details'];


        if ($purchase_data['id'] !== 0) {
            $gdata = $this->repository->whereId($purchase_data['id'])->getOne();
            if ($gdata->status_id != '0') {
                fail("订单状态[{$gdata->status->name}],禁止编辑");
                }
            }

        //退货
        if ($data['complaint_id'] == 2) {
            if (!is_array($data['details']) || count($data['details']) == 0)
                fail("退货必须选择库存！");
            }
        else {
            if (is_array($data['details']) && count($data['details']) > 0)
                fail("不应选择库存！");
            }
        // 折价
        if ($data['complaint_id'] == 4) {
            if (!is_numeric($data['discount'] ?? 'error') || $data['discount'] == 0)
                fail("折价必须填金额");
            $purchase_data['details'] = [
                [
                    'amount'      => $data['discount'],
                    'material_id' => $data['material_id'],
                    'type_id'     => $data['type_id'],
                    'lot_id'      => $data['lot_id'],
                    'color_id'    => $data['color_id'] ?? 0,
                    'dyelot'      => $data['dyelot'] ?? "",
                    'company_id'  => $data['company_id'],
                    'iscustomer'  => $data['iscustomer'],
                ]
            ];
            }

        $gdata = $this->repository->autosave($purchase_data);

        $gdata->details->filter(function ($v) use (&$gdata, $data)
            {
            $v->tax_id        = $gdata->tax_id;
            $v->code          = $gdata->code;
            $v->billdate      = $gdata->billdate;
            $v->company_id    = $gdata->company_id;
            $v->department_id = $data['department_id'];
            //采购白纱没有申请单号
            $v->purchase_apply_id = $data['purchase_apply_id'] ?? 0;
            $v->purchase_order_id = $data['purchase_order_id'] ?? 0;

            $v->amount                  = -$v->amount;
            $v->quantity                = -$v->quantity;
            $v->auxiliary_quantity      = -$v->auxiliary_quantity;
            $v->fect_quantity           = -$v->fect_quantity;
            $v->fect_auxiliary_quantity = -$v->fect_auxiliary_quantity;

            $v->se_quantity = $v->quantity;
            $v->se_amount   = $v->amount;
            $v->se_price    = $v->price;

            $v->save();
            $gdata->amount += $v->amount;
            $gdata->auxiliary_quantity += $v->auxiliary_quantity;
            $gdata->quantity += $v->quantity;

            });

        return $gdata->save();
        }



    protected function delete()
        {

        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->status_id != 0)
                fail("单据状态【{$v->status->name}】！不允许删除！");
            //删除明细
            $v->details->filter(function ($detail)
                {
                $detail->delete();
                });
            $v->delete();
            });
        }

    protected function audit()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->status_id != 0)
                fail("单据状态【{$v->status->name}】！不允许审核！");
            //删除明细
            $v->details->filter(function ($detail)
                {
                if ($detail->quantity < 0) {
                    $detail->useStorage("销售退货", $detail->code, -$detail->fect_quantity, -$detail->fect_auxiliary_quantity)->subStorage();
                    }
                auditSave($detail);
                });
            auditSave($v);
            });
        }
    protected function noaudit()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->status_id != 1)
                fail("单据状态【{$v->status->name}】！不允许反审！");
            //删除明细
            $v->details->filter(function ($detail)
                {
                if ($detail->quantity < 0) {
                    $detail->nosubStorage()->nouseStorage();
                    }
                auditSave($detail, false);
                });
            auditSave($v, false);
            });
        }
    protected function faudit()
        {
        $financeremark = request("financeremark");
        $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($order) use ($financeremark)
            {
            if ($order->status_id != 1) {
                fail("单据【{$order->code}】【{$order->status->name}】,审核失败！");
                }
            $order->financeremark = $financeremark;
            $order->details->filter(function ($v) use ($financeremark)
                {
                $v->financeremark = $financeremark;
                $v->save();
                });
            $order->finance();
            });
        }
    protected function nofaudit()
        {
        $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($order)
            {
            if ($order->status_id != 2) {
                fail("单据【{$order->code}】【{$order->status->name}】,审核失败！");
                }
            $order->nofinance();
            });
        }
    public function printReport()
        {
        $data = $this->repository->relation()->whereIn("id", $this->getRequestIds())->get();

        return createReport($data->toArray());
        }
    }